import {
  Button,
  Form,
  FormItem,
  Image,
  Input,
  InputNumber,
  message,
  Modal,
  Space,
  Spin
} from 'ant-design-vue'
import { defineComponent, onMounted, ref } from 'vue'

import { materialApi } from '@/apis'
import { IndexPicItem, IndexPicRes } from '@/apis/materialTypes'
import { ProTable, ProTableProps, ProTableRef } from '@/components'
import UploadFile from '@/components/UploadFile'
import { useBack, useDialog } from '@/hooks'

export default defineComponent({
  name: 'MinAppHomeManage',
  setup() {
    const { handleCancel } = useBack()

    const loading = ref(false)

    const indexPicData = ref({} as IndexPicRes)
    const curOptionItem = ref({} as IndexPicItem)
    const curOptionItemRef = ref({} as IndexPicItem)
    const showDialog = ref(false)
    const showDialogPop = ref(false)
    const saveLoading = ref(false)
    const topBanner = ref(true)

    const isAdd = ref(false)
    const tableTopRef = ref({} as ProTableRef)
    const tableMiddleRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: false,
      options: {
        border: true,
        align: 'center',
        columns: [
          {
            type: 'seq',
            width: 100,
            title: '序号'
          },
          {
            title: 'Banner图',
            slots: {
              default: 'image'
            }
          },
          {
            title: '操作',
            slots: {
              default: 'operation'
            },
            width: 150
          }
        ]
      }
    } as ProTableProps)
    onMounted(() => {
      getDetail()
    })

    //获取详情
    async function getDetail() {
      try {
        loading.value = true
        indexPicData.value = await materialApi.getIndexPic()
        if (!indexPicData.value) {
          indexPicData.value = {
            bannerListTemp: [],
            middleBannerListTemp: []
          } as IndexPicRes
        } else {
          if (indexPicData.value.banner) {
            let paths = [] as string[]
            if (indexPicData.value.bannerPath) {
              paths = indexPicData.value.bannerPath.split(',')
            }
            indexPicData.value.bannerListTemp = indexPicData.value.banner
              .split(',')
              .map((item, index) => {
                const path = paths.length > index ? paths[index] : ''
                return { img: item, path } as IndexPicItem
              })
          } else {
            indexPicData.value.bannerListTemp = []
          }

          if (indexPicData.value.middleBanner) {
            let paths = [] as string[]
            if (indexPicData.value.middleBannerPath) {
              paths = indexPicData.value.middleBannerPath.split(',')
            }
            indexPicData.value.middleBannerListTemp =
              indexPicData.value.middleBanner.split(',').map((item, index) => {
                const path = paths.length > index ? paths[index] : ''
                return { img: item, path } as IndexPicItem
              })
          } else {
            indexPicData.value.middleBannerListTemp = []
          }
        }
        loading.value = false
      } catch (e) {
        handleCancel()
      }
    }

    //编辑/新增弹窗
    function editOrAddPop() {
      curOptionItem.value.img = indexPicData.value.indexPopUp
      curOptionItem.value.path = indexPicData.value.indexPopUpPath
      showDialogPop.value = true
    }

    async function confirmEditOrAddPop() {
      indexPicData.value.indexPopUp = curOptionItem.value.img
      indexPicData.value.indexPopUpPath = curOptionItem.value.path
      showDialogPop.value = false
    }

    //编辑/新增商品
    function editOrAddBannerItem(isTopBanner, rowIndex) {
      isAdd.value = rowIndex == -1
      topBanner.value = isTopBanner
      if (isTopBanner) {
        if (isAdd.value) {
          curOptionItem.value = { sort: 1 } as IndexPicItem
        } else {
          const item = indexPicData.value.bannerListTemp[rowIndex]
          item.sort = rowIndex + 1
          Object.assign(curOptionItem.value, item)
          curOptionItemRef.value = item
        }
      } else {
        if (isAdd.value) {
          curOptionItem.value = { sort: 1 } as IndexPicItem
        } else {
          const item = indexPicData.value.middleBannerListTemp[rowIndex]
          item.sort = rowIndex + 1
          Object.assign(curOptionItem.value, item)
          curOptionItemRef.value = item
        }
      }

      showDialog.value = true
    }

    function confirmEditOrAddBannerItem() {
      if (!curOptionItem.value.img) {
        message.error('请选择Banner图片')
        return
      }

      let newIndex = curOptionItem.value.sort
      if (topBanner.value) {
        if (isAdd.value) {
          const item = Object.assign({}, curOptionItem.value)
          if (newIndex > indexPicData.value.bannerListTemp.length) {
            indexPicData.value.bannerListTemp.push(item)
          } else {
            indexPicData.value.bannerListTemp.splice(newIndex - 1, 0, item)
          }
        } else {
          if (newIndex > indexPicData.value.bannerListTemp.length) {
            newIndex = indexPicData.value.bannerListTemp.length
          }
          const oldIndex = curOptionItemRef.value.sort
          Object.assign(curOptionItemRef.value, curOptionItem.value)
          if (oldIndex != newIndex) {
            const temp = indexPicData.value.bannerListTemp[oldIndex - 1]
            indexPicData.value.bannerListTemp.splice(oldIndex - 1, 1)
            indexPicData.value.bannerListTemp.splice(newIndex - 1, 0, temp)
          }
        }
        tableTopRef.value.reload()
      } else {
        if (isAdd.value) {
          const item = Object.assign({}, curOptionItem.value)
          if (newIndex > indexPicData.value.middleBannerListTemp.length) {
            indexPicData.value.middleBannerListTemp.push(item)
          } else {
            indexPicData.value.middleBannerListTemp.splice(
              newIndex - 1,
              0,
              item
            )
          }
        } else {
          if (newIndex > indexPicData.value.middleBannerListTemp.length) {
            newIndex = indexPicData.value.middleBannerListTemp.length
          }
          const oldIndex = curOptionItemRef.value.sort
          Object.assign(curOptionItemRef.value, curOptionItem.value)
          if (oldIndex != newIndex) {
            const temp = indexPicData.value.middleBannerListTemp[oldIndex - 1]
            indexPicData.value.middleBannerListTemp.splice(oldIndex - 1, 1)
            indexPicData.value.middleBannerListTemp.splice(
              newIndex - 1,
              0,
              temp
            )
          }
        }
        tableMiddleRef.value.reload()
      }
      showDialog.value = false
    }

    //提交数据
    async function submit() {
      if (indexPicData.value.bannerListTemp.length == 0) {
        indexPicData.value.banner = ''
        indexPicData.value.bannerPath = ''
      } else {
        indexPicData.value.banner = indexPicData.value.bannerListTemp
          .map(item => item.img)
          .join(',')
        indexPicData.value.bannerPath = indexPicData.value.bannerListTemp
          .map(item => item.path)
          .join(',')
      }
      if (indexPicData.value.middleBannerListTemp.length == 0) {
        indexPicData.value.middleBanner = ''
        indexPicData.value.middleBannerPath = ''
      } else {
        indexPicData.value.middleBanner =
          indexPicData.value.middleBannerListTemp
            .map(item => item.img)
            .join(',')
        indexPicData.value.middleBannerPath =
          indexPicData.value.middleBannerListTemp
            .map(item => item.path)
            .join(',')
      }
      try {
        saveLoading.value = true
        await materialApi.editIndexPic(indexPicData.value)
        message.success('设置成功')
      } finally {
        saveLoading.value = false
      }
    }

    //删除
    function deleteBannerItem(isTopBanner, rowIndex) {
      showConfirm({
        content: '确认删除该Banner图？',
        onOk: () => {
          if (isTopBanner) {
            indexPicData.value.bannerListTemp.splice(rowIndex, 1)
            tableTopRef.value.reload()
          } else {
            indexPicData.value.middleBannerListTemp.splice(rowIndex, 1)
            tableMiddleRef.value.reload()
          }
        }
      })
    }

    const { showConfirm } = useDialog()

    return {
      loading,
      indexPicData,
      tableTopRef,
      tableMiddleRef,
      tableConfig,
      curOptionItem,
      showDialog,
      showDialogPop,
      isAdd,
      saveLoading,
      editOrAddPop,
      editOrAddBannerItem,
      deleteBannerItem,
      submit,
      confirmEditOrAddBannerItem,
      confirmEditOrAddPop
    }
  },
  render() {
    return (
      <div>
        <Spin spinning={this.loading}>
          <Form labelCol={{ span: 3 }} style={{ marginTop: '20px' }}>
            <FormItem label="首页弹框配置">
              <Space>
                <Button type="primary" onClick={this.editOrAddPop}>
                  编辑
                </Button>
                <Image
                  style={{ maxWidth: '100px' }}
                  v-model={[this.indexPicData.indexPopUp, 'src']}
                ></Image>
              </Space>
            </FormItem>
            <FormItem label="顶部banner" required>
              <Button
                type="primary"
                onClick={() => {
                  this.editOrAddBannerItem(true, -1)
                }}
              >
                新增
              </Button>
            </FormItem>

            <FormItem
              label=" "
              colon={false}
              v-show={this.indexPicData.bannerListTemp?.length > 0}
            >
              <ProTable
                data={this.indexPicData.bannerListTemp}
                ref="tableTopRef"
                style={{ width: '600px' }}
                v-slots={{
                  image: ({ row }) => <Image src={row.img}></Image>,
                  operation: ({ rowIndex }) => (
                    <Space>
                      <Button
                        type="link"
                        size="small"
                        onClick={() => this.deleteBannerItem(true, rowIndex)}
                      >
                        删除
                      </Button>
                      <Button
                        type="link"
                        size="small"
                        onClick={() => this.editOrAddBannerItem(true, rowIndex)}
                      >
                        编辑
                      </Button>
                    </Space>
                  )
                }}
                {...this.tableConfig}
              />
            </FormItem>
            <FormItem label="腰部banner">
              <Button
                type="primary"
                onClick={() => {
                  this.editOrAddBannerItem(false, -1)
                }}
              >
                新增
              </Button>
            </FormItem>

            <FormItem
              label=" "
              colon={false}
              v-show={this.indexPicData.middleBannerListTemp?.length > 0}
            >
              <ProTable
                data={this.indexPicData.middleBannerListTemp}
                ref="tableMiddleRef"
                style={{ width: '600px' }}
                v-slots={{
                  image: ({ row }) => <Image src={row.img}></Image>,
                  operation: ({ rowIndex }) => (
                    <Space>
                      <Button
                        type="link"
                        size="small"
                        onClick={() => this.deleteBannerItem(false, rowIndex)}
                      >
                        删除
                      </Button>
                      <Button
                        type="link"
                        size="small"
                        onClick={() =>
                          this.editOrAddBannerItem(false, rowIndex)
                        }
                      >
                        编辑
                      </Button>
                    </Space>
                  )
                }}
                {...this.tableConfig}
              />
            </FormItem>
            <FormItem label="积分上新背景图" required>
              <UploadFile
                v-model={[this.indexPicData.shangxinBackground, 'urls']}
              >
                上传图片
              </UploadFile>
            </FormItem>
            <FormItem label="公众号">
              <Space direction="vertical">
                <Input
                  v-model:value={this.indexPicData.article}
                  placeholder="请输入文案"
                  onBlur={this.onInputBlur}
                  onPressEnter={this.onInputBlur}
                  style={{ width: '400px' }}
                />
                <Input
                  v-model:value={this.indexPicData.articlePath}
                  placeholder="请输入文章地址"
                  onBlur={this.onInputBlur}
                  onPressEnter={this.onInputBlur}
                  style={{ width: '400px' }}
                />
              </Space>
            </FormItem>
            <FormItem label="积分不足文章">
              <Input
                v-model:value={this.indexPicData.underintegrationActicle}
                placeholder="请输入文章地址"
                onBlur={this.onInputBlur}
                onPressEnter={this.onInputBlur}
                style={{ width: '400px' }}
              />
            </FormItem>
            <FormItem label="会员等级不足文章">
              <Input
                v-model:value={this.indexPicData.insufficientLevelArticle}
                placeholder="请输入公众号文章地址"
                onBlur={this.onInputBlur}
                onPressEnter={this.onInputBlur}
                style={{ width: '400px' }}
              />
            </FormItem>
            <FormItem label=" " colon={false}>
              <Button
                loading={this.saveLoading}
                size="large"
                onClick={this.submit}
                type="primary"
              >
                保存
              </Button>
            </FormItem>
          </Form>
        </Spin>
        <Modal
          v-model:visible={this.showDialog}
          width={500}
          title={this.isAdd ? '新增' : '编辑'}
          destroyOnClose
          onOk={this.confirmEditOrAddBannerItem}
        >
          <Form labelCol={{ span: 5 }} style={{ marginTop: '15px' }}>
            <FormItem label={'Banner图片'} required>
              <UploadFile v-model={[this.curOptionItem.img, 'urls']}>
                上传图片
              </UploadFile>
            </FormItem>
            <FormItem label={'排序'} required>
              <InputNumber
                style={{ width: '300px' }}
                v-model:value={this.curOptionItem.sort}
                placeholder="请输入"
                maxlength={3}
                min={1}
              />
            </FormItem>
            <FormItem label={'path地址'}>
              <Input
                style={{ width: '300px' }}
                v-model:value={this.curOptionItem.path}
                placeholder="请输入"
              />
            </FormItem>
          </Form>
        </Modal>

        <Modal
          v-model:visible={this.showDialogPop}
          width={500}
          title={'编辑'}
          destroyOnClose
          onOk={this.confirmEditOrAddPop}
        >
          <Form labelCol={{ span: 5 }} style={{ marginTop: '15px' }}>
            <FormItem label={'弹窗图片'}>
              <UploadFile v-model={[this.curOptionItem.img, 'urls']}>
                上传图片
              </UploadFile>
            </FormItem>
            <FormItem label={'path地址'}>
              <Input
                style={{ width: '300px' }}
                v-model:value={this.curOptionItem.path}
                placeholder="请输入"
              />
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
})
